using System;
using System.Collections;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Context;
using PHSRAG.Insight21.FormsManagement;
using PHSRAG.Insight21.Policy;
using PHSRAG.Insight21.ScriptEngine;
using PHSRAG.Security.Enumerations;
using PHSRAG.Utility;
using ScriptReference = PHSRAG.Insight21.ScriptEngine.ScriptReference;

namespace PHSRAG.Insight21.COI
{
    /// <summary>
    /// COI History page displays the COIs specific to a user. The list includes
    /// all submitted, reviewed and in progress COIs.
    /// </summary>
    public partial class COIHistory : BasePage
    {
        #region Nested type: GridColumn

        private enum GridColumn
        {
            DocumentId,
            LastNotified,
            LastModified,
            Status
        }

        #endregion

        #region Constants

        private const string COIHistoryKey = "coiHistoryKey_C954F2AC-B5AD-4dbd-A8D1-126E7343D651";
        private const string ColumnId = "Id";
        private const string CurrentPageIndexKey = "currentPageIndexKey_C954F2AC-B5AD-4dbd-A8D1-126E7343D651";
        private const bool DefaultSortSequence = false; //true - ascending, false - descending
        private const string PageCacheKey = "pageCacheKey_C954F2AC-B5AD-4dbd-A8D1-126E7343D651";
        private const string SortColumnKey = "sortColumn_C954F2AC-B5AD-4dbd-A8D1-126E7343D651";
        private const string SortOrderKey = "sortOrder_C954F2AC-B5AD-4dbd-A8D1-126E7343D651";

        #endregion

        #region Instance Variables (Private)

        private int admPersonId;
        private ICachePolicy cachePolicy;
        private COICollection coiCollection;
        private ICachePolicy pageCachePolicy;

        #endregion

        #region Properties

        /// <summary>Gets or sets current page index for the grid</summary>
        private int CurrentPageIndex
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable;
                return (h == null || h[CurrentPageIndexKey] == null) ? 0 : (int) h[CurrentPageIndexKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable ?? new Hashtable();
                h[CurrentPageIndexKey] = value;
                coiHistoryGrid.CurrentPageIndex = value;
                pageCachePolicy.Cache(PageCacheKey, h);
            }
        }

        /// <summary>
        /// Gets or sets the name of the column on which the grid is sorted
        /// </summary>
        private string SortColumn
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable;
                return (h == null || h[SortColumnKey] == null) ? ColumnId : (string) h[SortColumnKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable ?? new Hashtable();
                h[SortColumnKey] = value;
                pageCachePolicy.Cache(PageCacheKey, h);
            }
        }

        /// <summary>
        /// Gets or sets the order of the sort
        /// </summary>
        private bool SortAscending
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable;
                return (h == null || h[SortOrderKey] == null) ? DefaultSortSequence : (bool) h[SortOrderKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable ?? new Hashtable();
                h[SortOrderKey] = value;
                pageCachePolicy.Cache(PageCacheKey, h);
            }
        }

        /// <summary>
        /// Get delegate status of the loggedIn user.
        /// </summary>
        private bool IsLoggedInUserADelegate
        {
            get
            {
                int loggedInUserId = ((UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey)).PersonId;
                return COIUserSummary.IsLoggedInUserADelegate(loggedInUserId, DataAccess.GetConnectionString());
            }
        }

        #endregion

        #region Page event handlers

        /// <summary>
        /// Displays all the COIs the user has ever filled. This page can be arrived at by 
        /// clicking into the My COI link or from the supervisor summary page. 
        /// 
        /// This page looks for cached person id. If so, it displays the name of the person in the breadcrumb
        /// based on the person id. 
        /// </summary>
        /// <param name="sender">Object that raised the event</param>
        /// <param name="e">Arguments associated with the event</param>
        protected void OnPageLoad(object sender, EventArgs e)
        {
            bool isSupervisorSummaryTab = false;
            try
            {
                string name = string.Empty;
                admPersonId = ((UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey)).PersonId;

                annunciator.Message = string.Empty;

                Hashtable incomingData = pageCachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
                if (incomingData != null)
                {
                    if (incomingData.ContainsKey(Keys.FullNameKey))
                    {
                        name = Convert.ToString(incomingData[Keys.FullNameKey]);
                    }
                    if (incomingData.ContainsKey(Keys.AdmPersonIdKey))
                    {
                        admPersonId = Convert.ToInt32(incomingData[Keys.AdmPersonIdKey]);
                        isSupervisorSummaryTab = true;
                    }
                }
                //there will be no incoming data if the My COI tab is highlighted

                if (name.Length > 0)
                {
                    breadCrumb.Add(
                        "COI History - " + name,
                        Settings.GetKeyValue("SubNavigation.CoI.COIHistoryURL", ""),
                        Settings.GetKeyValue("BreadCrumb.DetailPageLevel", 2));
                    helpContainer.Visible = false;
                    helpContainerSupervisor.Visible = true;
                }
                else
                {
                    breadCrumb.Add(
                        "COI History",
                        Settings.GetKeyValue("SubNavigation.CoI.COIHistoryURL", ""),
                        Settings.GetKeyValue("BreadCrumb.SummaryPageLevel", 1));
                }

                if (!Page.IsPostBack && postbackGuard.IsValid)
                {
                    coiHistoryGrid.PageSize = Settings.GetKeyValue("HumansDataGrid.ItemsPerPage", 20);
                    LoadDataGrid(admPersonId);
                    changeStatus.Attributes.Add("onclick", "javascript:return confirm('Do you really want to change the status?');");
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
            finally
            {
                coiSubNavigation.SelectedLink = isSupervisorSummaryTab ? "Supervisor Summary" : "My COI";

                coiSubNavigation.AccessLevel = ((UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey)).ModuleRoleBitmask;
                coiSubNavigation.IsLoggedInUserADelegate = IsLoggedInUserADelegate;
            }
        }

        #endregion

        #region Web Form Designer generated code

        /// <summary>
        /// Page Initialization.
        /// </summary>
        /// <param name="e">Arguments associated with the event</param>
        protected override void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
            cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
            pageCachePolicy = (Policy.ICachePolicy) Session[Policy.Names.PageCachePolicyKey];
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.header.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnNavigate);
            this.coiSubNavigation.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnCOISubNavigationNavigate);
            this.breadCrumb.Navigate += new System.Web.UI.WebControls.CommandEventHandler(this.OnNavigate);
            this.coiHistoryGrid.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.OnCOIHistoryGridItemCreated);
            this.coiHistoryGrid.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.OnHistoryGridItemCommand);
            this.coiHistoryGrid.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.OnCOIHistoryGridSort);
            this.coiHistoryGrid.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.OnHistoryGridItemDataBound);
            this.addNewCOI.Click += new ImageClickEventHandler(OnAddNewCOI);
            this.changeStatus.Click += new ImageClickEventHandler(OnChangeStatus);
            this.Load += new System.EventHandler(this.OnPageLoad);
            this.bottomPager.FirstPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnFirstPage);
            this.bottomPager.PreviousPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnPreviousPage);
            this.bottomPager.NextPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnNextPage);
            this.bottomPager.LastPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnLastPage);
            this.topPager.FirstPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnFirstPage);
            this.topPager.PreviousPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnPreviousPage);
            this.topPager.NextPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnNextPage);
            this.topPager.LastPage += new System.Web.UI.WebControls.CommandEventHandler(this.OnLastPage);
        }

        #endregion

        #region Private methods

        /// <summary>
        /// Displays an error message on the screen to the user with the exception, and all
        /// inner exception messages.
        /// </summary>
        /// <param name="ex">The exception to report on</param>
        private void DisplayExceptionReport(Exception ex)
        {
            annunciator.Title = InsightUtilities.Constants.Annunciator.Title;
            annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
        }

        /// <summary>
        /// Manages the top and bottom pagers
        /// </summary>
        private void ManagePagination()
        {
            int currentPageIndex = CurrentPageIndex;
            coiHistoryGrid.CurrentPageIndex = currentPageIndex;

            int startIndex = currentPageIndex*coiHistoryGrid.PageSize;

            bottomPager.FirstRecord = topPager.FirstRecord = startIndex + 1;
            bottomPager.LastRecord = topPager.LastRecord =
                Math.Min(startIndex + coiHistoryGrid.PageSize, coiHistoryGrid.VirtualItemCount);

            bottomPager.EnableFirstPage = topPager.EnableFirstPage =
                bottomPager.EnablePreviousPage = topPager.EnablePreviousPage =
                    (CurrentPageIndex != 0);

            bottomPager.EnableLastPage = topPager.EnableLastPage =
                bottomPager.EnableNextPage = topPager.EnableNextPage =
                    (CurrentPageIndex != (topPager.PageCount - 1));
        }

        /// <summary>
        /// Load COICollection, retrieve records to be displayed in the current page of the grid
        /// and bind them to the grid
        /// 
        /// If an In Progress COI already exists, then the Add New COI button will be disabled
        /// 
        /// The status change panel is only visible to super-users 
        /// </summary>
        /// <param name="admPersonId">Domain Id of the user whose COIs are to be viewed</param>
        private void LoadDataGrid(int admPersonId)
        {
            coiCollection = new COICollection(cachePolicy);
            coiCollection.Load(DataAccess.ConnectionString, admPersonId);

            

            //Hide the grid and the pagers if no records are found
            if (coiCollection.Count == 0)
            {
                annunciator.Message = "No COIs found for the user";
                topPager.Visible = bottomPager.Visible = coiHistoryGrid.Visible = false;
                //Enable the Add New COI button for superusers.
                if ((((UserContext)cachePolicy.GetCachedObject(UserContext.CacheKey)).ModuleRoleBitmask & (int)ModuleRoleBit.SuperUser) != 0)
                {
                    addNewCOI.Visible = true;
                }
            }
            else
            {
                topPager.Visible = bottomPager.Visible = coiHistoryGrid.Visible = true;
                coiHistoryGrid.VirtualItemCount = bottomPager.RecordCount = topPager.RecordCount = coiCollection.Count;

                int currentPageIndex = CurrentPageIndex;
                int pageCount = (topPager.RecordCount/coiHistoryGrid.PageSize) +
                    (((topPager.RecordCount%coiHistoryGrid.PageSize) == 0) ? 0 : 1);
                bottomPager.PageCount = topPager.PageCount = pageCount;
                bottomPager.CurrentPage = topPager.CurrentPage = currentPageIndex + 1;

                DataTable dt = coiCollection.GetPageCOIs(currentPageIndex*coiHistoryGrid.PageSize, coiHistoryGrid.PageSize, SortColumn, SortAscending);
                coiHistoryGrid.DataKeyField = ColumnId;
                coiHistoryGrid.DataSource = dt;
                coiHistoryGrid.DataBind();

                ManagePagination();

                //If current user is superuser, and 
                //		1. An In Progress COI exists, then allow the super-user to terminate it.
                //		2. A Submitted COI exists, then allow the super-user to change status to In Progress
                //      3. Make the AddNewCOI button visible for super users if an Annual COI is submited.
                if ((((UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey)).ModuleRoleBitmask & (int) ModuleRoleBit.SuperUser) != 0)
                {
                    if (coiCollection.DoesCOIExist(Constants.COIStatus.InProgress, Constants.COIType.AnnualCycle) || coiCollection.DoesCOIExist(Constants.COIStatus.Start, Constants.COIType.AnnualCycle))
                    {
                        statusChangeText.Text = "Terminate the current 'Start / In Progess' COI:";
                        statusChange.Visible = true;
                        addNewCOI.Visible = false;
                    }
                    else if (coiCollection.DoesCOIExist(Constants.COIStatus.Submitted, Constants.COIType.AnnualCycle) || coiCollection.DoesCOIExist(Constants.COIStatus.Reviewed, Constants.COIType.AnnualCycle))
                    {
                        statusChangeText.Text = "Change status of current 'Submitted' COI to 'In Progress':";
                        statusChange.Visible = true;
                        ////If an Annual COI is submitted or Reviewed, then only the AddNewCOI button is made visible
                        addNewCOI.Visible = true;
                    }
                    else if (coiCollection.DoesCOIExist(Constants.COIStatus.Terminated, Constants.COIType.AnnualCycle))
                    {
                         ////If an Annual COI is submitted, then only the AddNewCOI button is made visible
                        addNewCOI.Visible = true;
                        statusChange.Visible = false;
                    }
                }
            }
        }

        /// <summary>
        /// Remove the admpersonid and the username, if exists, from the cache
        /// Remove the pagecache
        /// </summary>
        private void UncacheUserDetails()
        {
            Hashtable incomingData = pageCachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
            if (incomingData != null)
            {
                if (incomingData.ContainsKey(Keys.FullNameKey))
                {
                    incomingData.Remove(Keys.FullNameKey);
                }
                if (incomingData.ContainsKey(Keys.AdmPersonIdKey))
                {
                    incomingData.Remove(Keys.AdmPersonIdKey);
                }
            }
            pageCachePolicy.UnCache(PageCacheKey);
        }

        #endregion

        #region Control event handlers

        /// <summary>
        /// Resets the subnavigation selected link before the header or the breadCrumb performs a redirect.
        /// </summary>
        /// <param name="sender">Control that raised the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnNavigate(object sender, CommandEventArgs e)
        {
            try
            {
                CurrentPageIndex = 0;
                SortColumn = ColumnId;
                SortAscending = true;
                coiSubNavigation.Reset();
                UncacheUserDetails();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Displays the sort symbol based on the sort column and order
        /// </summary>
        /// <param name="sender">Control that raised the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnCOIHistoryGridItemCreated(object sender, DataGridItemEventArgs e)
        {
            try
            {
                if (e.Item.ItemType == ListItemType.Header)
                {
                    Label sortSymbol = new Label();
                    sortSymbol.Text = (SortAscending) ? InsightUtilities.Constants.SortAscendingText : InsightUtilities.Constants.SortDescendingText;
                    sortSymbol.Font.Name = InsightUtilities.Constants.SortSymbolFontName;

                    Hashtable columnMap = new Hashtable();
                    foreach (DataGridColumn column in coiHistoryGrid.Columns)
                    {
                        columnMap[column.SortExpression] = coiHistoryGrid.Columns.IndexOf(column);
                    }

                    if (columnMap.ContainsKey(SortColumn))
                    {
                        (e.Item.Cells[(int) columnMap[SortColumn]]).Controls.Add(sortSymbol);
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Redirects the user to the COI Overview page if clicked on any status else redirects to the ViewReport page
        /// </summary>
        /// <param name="source">Control that raised the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnHistoryGridItemCommand(object source, DataGridCommandEventArgs e)
        {
            try
            {
                if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    int coiId = Convert.ToInt32(coiHistoryGrid.DataKeys[e.Item.ItemIndex]);
                    //Cache the Id of the selected COI
                    Hashtable outgoingCache = pageCachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable ?? new Hashtable();
                    outgoingCache[Keys.COIIdKey] = coiId;
                    //prepopulate individual disclosure form
                    if (e.CommandName == "OpenCOI")
                    {
                        ConflictOfInterest coi = new ConflictOfInterest(cachePolicy);
                        coi.Load(DataAccess.ConnectionString, coiId);
                        coi.LoadQuestionnaireAnswers();
                        ArrayList qAs = coi.QuestionnaireAnswers;
                        foreach (QuestionnaireAnswer qa in qAs)
                        {
                            if (qa.QuestionnaireCategory == FormsManagement.Constants.COICategory.InitialQuestionnaire)
                            {
                                if (qa.Status == Constants.QuestionnaireAnswerStatus.Start || qa.Status == "" || qa.Status == null)
                                {
                                    outgoingCache[Keys.QuestionnaireVersionIdKey] = qa.QuestionnaireVersionId;
                                    outgoingCache[Keys.QuesionnaireAnswerIdKey] = qa.Id;
                                    pageCachePolicy.Cache(Keys.IncomingDataKey, outgoingCache);
                                    Response.Redirect(Settings.GetKeyValue("SubNavigation.CoI.AnswerChartURL", ""), false);
                                }
                                else
                                {
                                    Response.Redirect(Settings.GetKeyValue("SubNavigation.CoI.OverviewChartURL", ""), false);
                                }
                                UpdateDisclosure(qa, coi);
                                break;
                            }
                        }
                        
                    }
                    //end of pre-population code
                    pageCachePolicy.Cache(Keys.IncomingDataKey, outgoingCache);


                    /*   if (e.CommandName == "ViewReport")
                    {
                        int docId = int.Parse(e.Item.Cells[(int)GridColumn.DocumentId].Text);
                        if (docId == 0)
                        {
                            Document report = ConflictOfInterest.GetReport(cachePolicy, Utility.DataAccess.ConnectionString,
                                Server.MapPath(""), coiId);
                            outgoingCache[Keys.DocumentKey] = report;
                        }
                        else
                        {
                            Document report = new Document(cachePolicy);
                            report.Load(Utility.DataAccess.ConnectionString, docId);
                            outgoingCache[Keys.DocumentKey] = report;
                        }

                        //Script for popup window that displays the attachment
                        string script = "\n<script language=JavaScript id='DisplayAttachment'>\n" +
                            "var confirmWin = null; \n" +
                            "winId = window.open('','ViewFile');" +
                            "if (winId != null) winId.close();" +
                            "confirmWin = window.open('../Research/DownloadForm.aspx', 'ViewFile', 'resizable=yes, status=yes, scrollbars=yes'); \n" +
                            "</script>";

                        //Check whether the script is already registered
                        if (!this.ClientScript.IsClientScriptBlockRegistered("DisplayAttachment"))
                        {
                            //Register the script
                            this.ClientScript.RegisterClientScriptBlock(GetType(), "DisplayAttachment", script);
                        }
                    }
                    else if (e.CommandName == "ViewDisclosure")
                    {
                        ConflictOfInterest coi = new ConflictOfInterest(cachePolicy);
                        coi.Load(Utility.DataAccess.ConnectionString, coiId);
                        Document report = coi.GetDisclosure(cachePolicy, Utility.DataAccess.ConnectionString,
                            Server.MapPath(""));
                        outgoingCache[Keys.DocumentKey] = report;

                        //Script for popup window that displays the attachment
                        string script = "\n<script language=JavaScript id='DisplayDisclosure'>\n" +
                            "var confirmWin = null; \n" +
                            "winId = window.open('','ViewDisclosure');" +
                            "if (winId != null) winId.close();" +
                            "confirmWin = window.open('../Research/DownloadForm.aspx', 'ViewDisclosure', 'resizable=yes, status=yes, scrollbars=yes'); \n" +
                            "</script>";

                        //Check whether the script is already registered
                        if (!this.ClientScript.IsClientScriptBlockRegistered("DisplayDisclosure"))
                        {
                            //Register the script
                            this.ClientScript.RegisterClientScriptBlock(GetType(), "DisplayDisclosure", script);
                        }
                    }*/
                    if (e.CommandName == "ReviewCOI")
                    {
                        int reviewerPersonId = ((UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey)).PersonId;
                        COIUserSummary.ReviewCOI(DataAccess.ConnectionString, Convert.ToInt32(e.CommandArgument), reviewerPersonId);
                        LoadDataGrid(admPersonId);
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// If the status of a COI is In Progess or Start, then only the supervisor or the person responsible to fill out the COI
        /// will see it as a link.
        /// </summary>
        /// <param name="sender">Control that raised the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnHistoryGridItemDataBound(object sender, DataGridItemEventArgs e)
        {
            try
            {
                if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    DataRowView dr = (DataRowView) e.Item.DataItem;
                    string status = dr.Row["Status"].ToString();
                    int coiId = ((int) dr.Row["Id"]);
                    int noteId = ((int) dr.Row["NoteId"]);
                    //Get COITypeId 
                    int COITypeId = (int)dr.Row["COITypeId"];
                    //Get DocumentId
                    int docId = (int) dr.Row["DocumentId"];
                    if (status == Constants.COIStatus.Start)
                    {
                        if (admPersonId == ((UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey)).PersonId ||
                            ((((UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey)).ModuleRoleBitmask & (int) ModuleRoleBit.SuperUser) != 0))
                        {
                            if (
                                (COITypeId == (int)Constants.COIType.RealTimeUpdate)
                                &&
                                (coiCollection.DoesCOIExist(Constants.COIStatus.InProgress, Constants.COIType.AnnualCycle) || coiCollection.DoesCOIExist(Constants.COIStatus.Start, Constants.COIType.AnnualCycle))
                               )
                            {
                                (e.Item.FindControl("imgbtnUpdate")).Visible = false;
                            }
                            else
                            {
                                (e.Item.FindControl("imgbtnUpdate")).Visible = true;
                            }
                        }
                        //pdfs for COI in start status are not visible to anyone
                        e.Item.FindControl("report").Visible = false;
                        e.Item.FindControl("disclosure").Visible = false;
                    }
                    else if (status == Constants.COIStatus.InProgress)
                    {
                        if (admPersonId == ((UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey)).PersonId ||
                            ((((UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey)).ModuleRoleBitmask & (int) ModuleRoleBit.SuperUser) != 0))
                        {

                            if (
                                (COITypeId == (int)Constants.COIType.RealTimeUpdate)
                                &&
                                (coiCollection.DoesCOIExist(Constants.COIStatus.InProgress, Constants.COIType.AnnualCycle) || coiCollection.DoesCOIExist(Constants.COIStatus.Start, Constants.COIType.AnnualCycle))
                               )
                            {
                                (e.Item.FindControl("imgbtnUpdate")).Visible = false;
                            }
                            else
                            {
                                (e.Item.FindControl("imgbtnUpdate")).Visible = true;
                            }
                            //(e.Item.FindControl("imgbtnUpdate")).Visible = true;
                            e.Item.FindControl("report").Visible = true;
                            e.Item.FindControl("disclosure").Visible = true;
                        }
                        else
                        {
                            //InProgress report is visible only to the super-user or the owner
                            e.Item.FindControl("report").Visible = false;
                            e.Item.FindControl("disclosure").Visible = false;
                        }
                    }
                    else if ((status == Constants.COIStatus.Submitted)
                        && (admPersonId != ((UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey)).PersonId))
                    {
                        e.Item.FindControl("reviewCOI").Visible = true;
                    }
                    LinkButton addViewNotes = e.Item.FindControl("addViewNotes") as LinkButton;
                    bool canAddNotes = (status != Constants.COIStatus.Submitted) ? false : true;
                    addViewNotes.OnClientClick = "javascript:window.open('AddNote.aspx?COIId=" + coiId + "&CanAdd=" + canAddNotes + "', 'AddCOI', 'width = 700, height = 550, toolbar = no, resizable=no, status=yes, scrollbars=yes');return false;";

                    if (noteId == 0)
                    {
                        if (status != Constants.COIStatus.Submitted)
                        {
                            addViewNotes.Visible = false;
                        }
                    }
                    else
                    {
                        if (status != Constants.COIStatus.Submitted)
                        {
                            addViewNotes.Text = "View";
                        }
                    }

                    /*Remove postback from View Report link*/

                    LinkButton lnkReport = (LinkButton) e.Item.FindControl("report");
                    if (lnkReport.Visible)
                    {
                        lnkReport.OnClientClick = "javascript:window.open('../Research/DownloadForm.aspx?Report=ViewReport&CoiId=" + coiId + "&DocId=" + docId + "', 'ViewReport', 'resizable=yes, status=yes, scrollbars=yes');return false;";
                    }
                    /*Remove postback from view Disclosure link*/

                    LinkButton lnkDisclosure = (LinkButton) e.Item.FindControl("disclosure");
                    if (lnkDisclosure.Visible)
                    {
                        lnkDisclosure.OnClientClick = "javascript:window.open('../Research/DownloadForm.aspx?Report=ViewDisclosure&CoiId=" + coiId + "&DocId=" + docId + "', 'ViewDisclosure', 'resizable=yes, status=yes, scrollbars=yes');return false;";
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Uncache the user details and the pagecache upon navigating to a different page
        /// </summary>
        /// <param name="sender">Control that raised the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnCOISubNavigationNavigate(object sender, CommandEventArgs e)
        {
            try
            {
                UncacheUserDetails();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Handler for the event raised when the FirstPage link in clicked in the Pager control.
        /// Set the current page index to 0, bind the datagrid with data and manage navigation links. To avoid superfluous
        /// data binding activites, no action is taken if the current page index is already 0.
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Arguments associated with the event</param>
        private void OnFirstPage(object sender, CommandEventArgs e)
        {
            try
            {
                CurrentPageIndex = 0;
                LoadDataGrid(admPersonId);
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Handler for the event raised when the PreviousPage link in clicked in the Pager control.
        /// Decrement the current page index, bind the datagrid with data and manage navigation links.
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Arguments associated with the event</param>
        private void OnPreviousPage(object sender, CommandEventArgs e)
        {
            try
            {
                --CurrentPageIndex;
                LoadDataGrid(admPersonId);
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Handler for the event raised when the NextPage link in clicked in the Pager control.
        /// Increment the current page index, bind the datagrid with data and manage navigation links.
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Arguments associated with the event</param>
        private void OnNextPage(object sender, CommandEventArgs e)
        {
            try
            {
                ++CurrentPageIndex;
                LoadDataGrid(admPersonId);
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Handler for the event raised when the LastPage link in clicked in the Pager control.
        /// Set the current page index to one less than the total page count (index is 0-based), bind the datagrid with
        /// data and manage navigation links. To avoid superfluous data binding activites, no action is taken if the current
        /// page index is already corresponding to the last page.
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Arguments associated with the event</param>
        private void OnLastPage(object sender, CommandEventArgs e)
        {
            try
            {
                CurrentPageIndex = topPager.PageCount - 1;
                LoadDataGrid(admPersonId);
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Handler for the event raised when a column header within the data grid is clicked.
        /// Set the current page index to 0, load the data grid, and initialize the pager. We set the page index to 0
        /// since sorting implies sorting of the entrie data and NOT sorting what is visible.
        /// </summary>
        /// <param name="source">Object that raised the event</param>
        /// <param name="e">Arguments associated with the event</param>
        private void OnCOIHistoryGridSort(object source, DataGridSortCommandEventArgs e)
        {
            try
            {
                if (e.SortExpression != string.Empty)
                {
                    CurrentPageIndex = 0;
                    SortAscending = (SortColumn == e.SortExpression) ? !SortAscending : DefaultSortSequence;
                    SortColumn = e.SortExpression;
                    LoadDataGrid(admPersonId);
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Add a new COI with the status set to 'Start' and reloads the grid
        /// </summary>
        /// <param name="sender">Object that raised the event</param>
        /// <param name="e">Arguments associated with the event</param>
        private void OnAddNewCOI(object sender, ImageClickEventArgs e)
        {
            try
            {
                //When a superuser clicks on "AddNew" then its considered as an openrollment.
                COICollection.AddNewCOI(cachePolicy, admPersonId, Constants.COIDateType.None, Constants.COIType.AnnualCycle, Constants.NotificationTypes.OpenEnrollment);

                LoadDataGrid(admPersonId);
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        ///If current user is superuser, and 
        ///	1. A Start or an In Progress COI exists, then terminate it.
        ///	2. A Submitted COI exists, then change status to In Progress
        /// </summary>
        /// <param name="sender">Object that raised the event</param>
        /// <param name="e">Arguments associated with the event</param>
        private void OnChangeStatus(object sender, ImageClickEventArgs e)
        {
            try
            {
                coiCollection = new COICollection(cachePolicy);
                coiCollection.Load(DataAccess.ConnectionString, admPersonId);

                if (coiCollection.DoesCOIExist(Constants.COIStatus.InProgress,Constants.COIType.AnnualCycle) || coiCollection.DoesCOIExist(Constants.COIStatus.Start,Constants.COIType.AnnualCycle))
                {
                    ConflictOfInterest coi = coiCollection.GetStartOrInProgressCOI();
                    coi.Status = Constants.COIStatus.Terminated;
                    coi.Save(DataAccess.ConnectionString, Constants.COIDateType.None);
                    coi.AuditCOIChanges(Constants.COIActionsForAudit.Terminate);
                }
                else if (coiCollection.DoesCOIExist(Constants.COIStatus.Submitted,Constants.COIType.AnnualCycle))
                {
                    ConflictOfInterest coi = coiCollection.GetLastSubmittedCOI();
                    coi.Status = Constants.COIStatus.InProgress;
                    coi.DateSubmitted = DateTime.MinValue;
                    coi.Report.Delete(DataAccess.ConnectionString);
                    coi.DocumentId = 0;
                    coi.Save(DataAccess.ConnectionString, Constants.COIDateType.None);
                    coi.AuditCOIChanges(Constants.COIActionsForAudit.ResetToInProgress);
                }
                LoadDataGrid(admPersonId);
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }
        /// <summary>
        /// Updates the corresponding disclosure form
        /// </summary>
        private void UpdateDisclosure(QuestionnaireAnswer questAnswer, ConflictOfInterest coi)
        {
            Script answerFillerScript =
                (Script) questAnswer.QuestionnaireVersion.Scripts[FormsManagement.Constants.ScriptType.AnswerFiller];

            if (answerFillerScript != null)
            {
                using (ScriptEngineHost scriptHost =
                    new ScriptEngineHost(
                        string.Format("{0}{1}", questAnswer.QuestionnaireVersionId,
                            ScriptEngine.Constants.RootMoniker.AnswerFillerScriptMoniker),
                        ScriptEngine.Constants.RootNamespaces.AnswerFillerScript,
                        true))
                {
                    ArrayList refs = ScriptReference.GetAllScriptReferences(
                        DataAccess.GetConnectionString());

                    for (int i = 0; i < refs.Count; ++i)
                    {
                        ScriptReference reference = (ScriptReference) refs[i];
                        scriptHost.AddDLLReference(reference.Path);
                    }


                    // add the connection string
                    scriptHost.AddIntrinsicObject(ScriptEngine.Constants.Instrinsics.ConnectionString,
                        DataAccess.GetConnectionString());
                    // add the caching policy
                    scriptHost.AddIntrinsicObject(ScriptEngine.Constants.Instrinsics.CachePolicy, cachePolicy);
                    // add this COI as an intrinsic.
                    scriptHost.AddIntrinsicObject(ScriptEngine.Constants.Instrinsics.COI, coi);
                    // add the QuestionnaireAnswer
                    scriptHost.AddIntrinsicObject(ScriptEngine.Constants.Instrinsics.QuestionnaireAnswer,
                        questAnswer);
                    // add the params
                    COIParams coiParams = new COIParams();
                    coiParams.OutsideEntityName = questAnswer.Name;
                    coiParams.OutsideEntitySelectedValue = questAnswer.ExternalId;
                    coiParams.MarkForDeletion = true;
                    scriptHost.AddIntrinsicObject(ScriptEngine.Constants.Instrinsics.COIParams,
                        coiParams);


                    // compile and run the script.
                    if (scriptHost.Compile(answerFillerScript))
                    {
                        scriptHost.RunScript(answerFillerScript,
                            ScriptEngine.Constants.AssemblyType.AnswerFillerScript,
                            ScriptEngine.Constants.MethodsToRun.Main);
                    }

                    return;
                }
            }
        }

        #endregion
    }
}